import React, { Component } from 'react';
import { connect } from 'dva';
import { Tree, Row, Col, message, Spin, Button, Tag } from 'antd';
import style from './menuRight.less';

const { TreeNode } = Tree;

@connect(({ menuRightModel, loading }) => ({
  menuRightModel,
  loading: loading.models.menuRightModel,
}))
class menuRight extends Component {
  state = {
    roleData: [],
    roleDefaultSelectedKeys: [],
    roleSelectName: '',
    menuData: [],
    menuDefaultCheckedKeys: [],
    menuDefaultSelectedKeys: [],
    hideMenu: false,
    loading: true,
    buttonDataSource: [],
    buttonDefaultCheckedKeys: [],
  };

  componentDidMount() {
    const { dispatch } = this.props;
    const thisCtx = this;

    /**
     *  获取角色列表
     * @Author 肖家添
     * @Date 2019/5/12 16:45
     */
    dispatch({
      type: 'systemMenuModel/getRoleMenu',
      callback: function(data) {
        if (data.success) {
          if (data.datas != null && data.datas.length > 0) {
            let key = data.datas[0].key;
            let title = data.datas[0].title;
            thisCtx.setState({
              roleDefaultSelectedKeys: [key + ''],
              roleSelectName: title,
            }, function(){
              thisCtx.getRightList({});
            });

          }
          thisCtx.setState({ roleData: data.datas });
        } else {
          thisCtx.loading(false);
          message.error('获取角色列表失败，日志：' + data.msg);
        }
      },
    });
  }

  /**
   *  获取角色权限
   * @Author 肖家添
   * @Date 2019/5/12 16:45
   */
  getRightList({loading = true, loaderCallBack}) {
    const { dispatch } = this.props;
    const thisCtx = this;
    const { roleDefaultSelectedKeys } = thisCtx.state;
    const roleId = roleDefaultSelectedKeys[0];
    thisCtx.loading(loading);
    thisCtx.setState({ hideMenu: loading });
    dispatch({
      type: 'menuRightModel/getRightList',
      payload: { roleId: roleId },
      callback: function(data) {
        if (data.success) {
          const datas = data.datas;
          let menuRightKeys = new Array(), buttonRightKeys = new Array();
          if (datas != null && datas.length > 0) {
            for (let i = 0; i < datas.length; i++) {
              const item = datas[i],
                menuId = item.mmId + "",
                rightType = item.type;
              if(rightType == 1){  // 菜单权限
                menuRightKeys.push(menuId);
              }else if(rightType == 2){  // 按钮权限
                buttonRightKeys.push(menuId);
              }
            }
          }
          thisCtx.setState({
            hideMenu: false,
            menuDefaultCheckedKeys: menuRightKeys,
            buttonDefaultCheckedKeys: buttonRightKeys
          });
          if(loading) thisCtx.getMenu();
          else if(loaderCallBack) loaderCallBack();
        } else {
          thisCtx.loading(false);
          message.error('获取角色权限失败，日志：' + data.msg);
        }
      }
    });
  }

  /**
   * 获取系统树形菜单
   * @Author 肖家添
   * @Date 2019/5/12 16:45
   */
  getMenu() {
    const { menuData } = this.state;
    const { dispatch } = this.props;
    const thisCtx = this;

    if (menuData == null || menuData.length <= 0) {
      dispatch({
        type: 'menuRightModel/getSysMenu',
        payload: { getMenuAllByTree: true },
        callback: function(data) {
          if (data.success) {
            const datas = data.datas, menuDefaultSelectedKeys = [];
            if(datas && datas.length > 0){
              menuDefaultSelectedKeys[0] = datas[0].key.toString();
              thisCtx.getButtonsByMenuId(datas[0].key);
            }
            thisCtx.setState({
              menuData: datas,
              menuDefaultSelectedKeys
            });
          } else {
            message.error('获取系统菜单失败，日志：' + data.msg);
          }
          thisCtx.loading(false);
        },
      });
    } else {
      thisCtx.loading(false);
    }
  }

  /**
   * 根据菜单Id获取按钮
   * @Author 肖家添
   * @Date 2020/3/10 22:39
   */
  getButtonsByMenuId = (menuId) => {
    const { dispatch } = this.props, that = this;
    const { roleDefaultSelectedKeys } = that.state;
    const roleId = roleDefaultSelectedKeys[0];
    dispatch({
      type: "menuButtonsModel/moduleList",
      payload: {menuId: menuId},
      callback: function(data){
        if(data.success){
          const datas = data.datas;
          that.setState({
            buttonDataSource: datas
          });
        }
      }
    });
  }

  /**
   *  加载层
   * @Author 肖家添
   * @Date 2019/5/12 17:44
   */
  loading(state) {
    this.setState({ loading: state });
  }

  /**
   *  角色菜单选中事件
   * @Author 肖家添
   * @Date 2019/5/12 15:35
   */
  onRoleTreeSelect = (roleDefaultSelectedKeys, ele) => {
    if (roleDefaultSelectedKeys != null && roleDefaultSelectedKeys.length > 0) {
      let key = roleDefaultSelectedKeys[0];
      const that = this;
      const { roleData } = that.state;
      for (let i = 0; i < roleData.length; i++) {
        if (roleData[i].key == key) {
          this.setState({ roleSelectName: roleData[i].title });
        }
      }
      that.setState({ roleDefaultSelectedKeys }, function () {
        that.getRightList({});
      });
    }
  };

  /**
   * 菜单列表复选框选中事件
   * @Author 肖家添
   * @Date 2019/5/12 18:09
   */
  onMenuCheck = menuDefaultCheckedKeys => {
    console.log(menuDefaultCheckedKeys.checked);
    this.setState({ menuDefaultCheckedKeys: menuDefaultCheckedKeys.checked });
  };

  /**
   * 按钮复选框选中时间
   * @Author 肖家添
   * @Date 2020/3/10 22:57
   */
  onButtonCheck = buttonDefaultCheckedKeys => {
    this.setState({ buttonDefaultCheckedKeys: buttonDefaultCheckedKeys });
  };

  /**
   * 保存菜单权限
   * @Author 肖家添
   * @Date 2019/5/12 18:12
   */
  onSaveMenuRight() {
    const { roleDefaultSelectedKeys, menuDefaultCheckedKeys, buttonDefaultCheckedKeys } = this.state;
    if (roleDefaultSelectedKeys != null && roleDefaultSelectedKeys.length > 0) {
      const thisCtx = this;
      const { dispatch } = this.props;

      let roleId = roleDefaultSelectedKeys[0];
      let requestData = 'roleId=' + roleId;
      let menusLength = menuDefaultCheckedKeys.length;
      for (let i = 0; i < menusLength; i++) {
        requestData += `&menuId=${menuDefaultCheckedKeys[i]}`;
      }
      for (let i = 0; i < buttonDefaultCheckedKeys.length; i++) {
        const key = buttonDefaultCheckedKeys[i];
        if(key == "-9999") continue;
        requestData += `&buttonId=${key}`;
      }
      thisCtx.loading(true);
      dispatch({
        type: 'menuRightModel/saveMenuRight',
        payload: { data: requestData },
        callback: function(data) {
          thisCtx.loading(false);
          if (data.success) {
            message.info('保存成功');
          } else {
            message.info(data.msg);
          }
        },
      });
    }
  }

  render() {
    const {
      roleData,
      menuData,
      roleDefaultSelectedKeys,
      menuDefaultCheckedKeys,
      buttonDefaultCheckedKeys,
      hideMenu,
      roleSelectName,
      buttonDataSource,
      menuDefaultSelectedKeys
    } = this.state;
    const thisCtx = this;
    /**
     *  循环节点
     * @Author 肖家添
     * @Date 2019/5/12 16:38
     */
    const loop = data =>
      data.map(item => {
        const title = <span>{item.title}</span>;

        if (item.children) {
          return (
            <TreeNode key={item.key} title={title}>
              {loop(item.children)}
            </TreeNode>
          );
        }
        return <TreeNode key={item.key} title={title}/>;
      });

    /**
     *  角色视图
     * @Author 肖家添
     * @Date 2019/5/12 16:38
     */
    const roleHTML = function() {
      if (roleData.length > 0 && roleDefaultSelectedKeys.length > 0) {
        return (
          <div>
            <Tree defaultSelectedKeys={roleDefaultSelectedKeys} onSelect={thisCtx.onRoleTreeSelect}>
              {loop(roleData)}
            </Tree>
          </div>
        );
      } else {
        return;
      }
    };

    /**
     *  菜单视图
     * @Author 肖家添
     * @Date 2019/5/12 16:43
     */
    const menuHTML = function() {
      if (!hideMenu && menuData.length > 0) {
        return (
          <div>
            <Tree
              checkable
              defaultExpandAll={true}
              defaultSelectedKeys={menuDefaultSelectedKeys}
              defaultCheckedKeys={menuDefaultCheckedKeys}
              onCheck={thisCtx.onMenuCheck}
              checkStrictly={true}
              onSelect={(keys) => {
                if(keys.length == 1){
                  thisCtx.setState({menuDefaultSelectedKeys: keys}, function(){
                    thisCtx.getRightList({
                      loading: false,
                      loaderCallBack: function(){
                        thisCtx.getButtonsByMenuId(keys[0]);
                      }
                    });
                  });
                }
              }}
            >
              {loop(menuData)}
            </Tree>
          </div>
        );
      } else {
        return;
      }
    };

    /**
     * 按钮视图
     * @Author 肖家添
     * @Date 2020/3/10 22:30
     */
    const buttonHTML = function() {
      if (!hideMenu && menuData.length > 0) {
        if(buttonDataSource.length <= 0) return <Tag color="magenta">暂无按钮</Tag>
        return (
          <div>
            <Tree
              checkable
              defaultExpandAll={true}
              defaultCheckedKeys={buttonDefaultCheckedKeys}
              onCheck={thisCtx.onButtonCheck}
              checkStrictly={false}
            >
              <TreeNode key={"-9999"} title={"全选"}>
                {buttonDataSource.map(item => <TreeNode key={item.id} title={item.name}/>)}
              </TreeNode>
            </Tree>
          </div>
        );
      } else {
        return;
      }
    };

    return (
      <Spin spinning={this.state.loading}>
        <Row gutter={18} className={style.body}>
          <Col span={24}>
            <div className={style.menuButtonsDiv}>
              <Button type="primary" onClick={() => thisCtx.onSaveMenuRight()}>
                保存
              </Button>
              <span style={{ marginLeft: 15 }}>{`已选中 ${roleSelectName}`}</span>
            </div>
          </Col>
          <Col xs={12} sm={12} md={6} lg={6} xl={6}>
            {roleHTML()}
          </Col>
          <Col xs={12} sm={12} md={6} lg={6} xl={6}>
            <h2>菜单权限</h2>
            {menuHTML()}
          </Col>
          <Col xs={12} sm={12} md={6} lg={6} xl={6}>
            <h2>按钮权限</h2>
            {buttonHTML()}
          </Col>
        </Row>
      </Spin>
    );
  }
}

export default menuRight;
